package com.faxsun.controller.uc.entity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ws.rs.core.Response;

import org.broadleafcommerce.core.web.api.BroadleafWebServicesException;

import com.faxsun.api.endpoint.account.CommonEndpointConstants;


public class RestfulProcessor {
	
	public static void authenticationCheck(String codes){
		int result = check(codes);
		if(result == -1){
			throw BroadleafWebServicesException.build(
					Response.Status.UNAUTHORIZED.getStatusCode()).addMessage(CommonEndpointConstants.CODE_FORMAT_ERROR);
		}else if(result == -2){
			throw BroadleafWebServicesException.build(
					Response.Status.UNAUTHORIZED.getStatusCode()).addMessage(CommonEndpointConstants.TIMEOUT_ERROR);
		}else if(result == -3){
			throw BroadleafWebServicesException.build(
					Response.Status.UNAUTHORIZED.getStatusCode()).addMessage(CommonEndpointConstants.AUTHENTICATION_FAIL);
		}
	}
	
	
	/*
	 * -1 : checked string format error. [uuid+nonce+timeStramp+api_sig] 
	 * -2 : time out. 
	 * -3 : authentication fail.
	 */	
	private static int check(String str){
		if(str != null && !str.isEmpty()){			
			String[ ] afterSplit= new String[4]; 
			afterSplit=str.split("+");			
			String uuid = afterSplit[0];
			String nonce = afterSplit[1];
			String time = afterSplit[2];
			String api_sig = afterSplit[3];
			if(uuid == null || uuid.isEmpty() || nonce ==null || nonce.isEmpty() || time == null 
					|| time.isEmpty() || api_sig == null || api_sig.isEmpty()) {
				return -1;
			}
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Date date;
			try {
				date = sdf.parse(time);
				if(AssistTool.timeoutCheck(date, 60)){
					return -2;
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
			// fix		
			String api_key = "";
			String api_secret = "";
			String sig = AssistTool.getApi_sigMD5(api_key, nonce, time, uuid, api_secret);
			if(sig.equals(api_sig)){
				return 0;
			}else{
				return -3;
			}
		}
		return -1;	
	}
}
